(function(){
    var ChannelDetector = function(){
        this.channelMapper = {
            homePage: {n:'homePage'},
	        shows: {n:'shows',sub:{'shows_vogueshow_trends':{n:'vogueshow_trends'},'shows_designer':{n:'fashion_designer'},'shows_style_notes':{n:'style_notes'},'shows_fashion_story':{n:'fashion_story'},'shows_celebrity':{n:'celebrity'},'shows_look_update':{n:'look_update'},'shows_local_designer':{n:'local_designer'}}},
            fashion:{n:'fashion',sub:{'fashion_mix_match':{n:'mix_match'},'fashion_hot_buy':{n:'hot_buy'},'fashion_fashion_trends':{n:'fashion_trends'},'fashion_accessory':{n:'accessory'},'fashion_fashion_star':{n:'fashion_star'},'fashion_street_chic':{n:'street_chic'},'fashion_belongings':{n:'belongings'},'fashion_fashion_feature':{n:'fashion_feature'},'fashion_fashion_news':{n:'fashion_news'},'fashion_fashion_gallary':{n:'fashion_gallary'},'fashion_wardrobe':{n:'wardrobe'}}},
            trends:{n:'trends',sub:{'trends_mix_match':{n:'mix_match'},'trends_hot_buy':{n:'hot_buy'},'trends_fashion_trends':{n:'fashion_trends'},'trends_accessory':{n:'accessory'},'trends_fashion_star':{n:'fashion_star'},'trends_street_chic':{n:'street_chic'},'trends_belongings':{n:'belongings'},'trends_fashion_feature':{n:'fashion_feature'},'trends_fashion_news':{n:'fashion_news'},'trends_fashion_gallary':{n:'fashion_gallary'},'trends_wardrobe':{n:'wardrobe'}}},
            beauty:{n:'beauty',sub:{'beauty_firstlook':{n:'firstlook'},'beauty_beauty_star':{n:'beauty_star'},'beauty_skincare':{n:'skincare'},'beauty_makeup':{n:'makeup'},'beauty_perfume':{n:'perfume'},'beauty_hair':{n:'hair'},'beauty_beauty_gallary':{n:'beauty_gallary'},'beauty_body_health':{n:'body_health'},'beauty_beauty_feature':{n:'beauty_feature'},'beauty_beauty_news':{n:'beauty_news'},'beauty_QA':{n:'QA'},'beauty_vogue_love':{n:'vogue_love'},'beauty_brand_story':{n:'brand_story'}}},
	        people:{n:'people',sub:{'people_interview':{n:'interview'},'people_streetchic':{n:'streetchic'},'people_model':{n:'model'},'people_designer':{n:'designer'},'people_celebrity':{n:'celebrity'},'people_gallary':{n:'gallary'},'people_party':{n:'party'},'people_special_feature':{n:'special_feature'},'people_contributor':{n:'contributor'}}},
	        jewel:{n:'jewel',sub:{'jewel_top_jewelry':{n:'top_jewelry'},'jewel_new_jewelry':{n:'new_jewelry'},'jewel_new_boutique':{n:'new_boutique'},'jewel_brand_event':{n:'brand_event'},'jewel_jewelry_trade':{n:'jewelry_trade'},'jewel_celebrity_jewelry':{n:'celebrity_jewelry'},'jewel_jewelry_history':{n:'jewelry_history'},'jewel_famous_watch':{n:'famous_watch'},'jewel_new_watch':{n:'new_watch'},'jewel_watch_boutique':{n:'watch_boutique'},'jewel_celebrity_watch':{n:'celebrity_watch'},'jewel_fashion_watch':{n:'fashion_watch'},'jewel_watch_trade':{n:'watch_trade'},'jewel_watch_culture':{n:'watch_culture'}}},
	        feature:{n:'feature',sub:{'feature_special':{n:'special'},'feature_2010zt':{n:'2010zt'}}},
	        info:{n:'info',sub:{'info_lifestyle':{n:'lifestyle'}}},	
            video:{n:'video',sub:{'video_Video_FengGeHui':{n:'Video_FengGeHui'},'video_Video_ShiZhuangXiuChang':{n:'Video_ShiZhuangXiuChang'},'video_Video_ShiZhuangPaiDui':{n:'Video_ShiZhuangPaiDui'}}},
	        gallery:{n:'gallery'},
	        bbs:{n:'bbs'},
	        blog:{n:'blog'},
	        order_vogue:{n:'order_vogue'},
	        rss:{n:'rss'},
	        chinadaily: {n:'chinadaily_shows',sub:{'chinadaily_trends':{n:'trends'},'chinadaily_shows':{n:'shows'}}},
	        whatsvogue:{n:'whatsvogue',sub:{'whatsvogue_vogueworld':{n:'vogueworld'},'whatsvogue_coverstory':{n:'coverstory'},'whatsvogue_event':{n:'event'},'whatsvogue_contributor':{n:'contributor'},'whatsvogue_magzine':{n:'magzine'},'whatsvogue_contributor':{n:'contributor'},'whatsvogue_new_issue':{n:'new_issue'},'whatsvogue_subscriptions':{n:'subscriptions'},'whatsvogue_local_designer':{n:'local_designer'}}},
            invogue: {n:'invogue',sub:{
              'invogue_voguestylist':{n:'invogue_voguestylist', sub:{
                'invogue_voguestylist_mixmatch':{n: "mixmatch"},
                'invogue_voguestylist_stylecollage':{n: "stylecollage"},
                'invogue_voguestylist_bestdressed':{n: "bestdressed"},
                'invogue_voguestylist_streetchic':{n: "streetchic"},
                'invogue_voguestylist_newclassics':{n: "newclassics"}
              }},
              'invogue_editorchoices':{n:'invogue_editorchoices', sub:{
                'invogue_editorchoices_hotlist':{n: "hotlist"},
                'invogue_editorchoices_celebritypicks':{n: "celebritypicks"},
                'invogue_editorchoices_keypieces':{n: "keypieces"},
                'invogue_editorchoices_mostwanted':{n: "mostwanted"}
              }},
              'invogue_fashiontopics':{n:'invogue_fashiontopics', sub:{
                'invogue_fashiontopics_designchina':{n: "designchina"},
                'invogue_fashiontopics_fashioninsider':{n: "fashioninsider"},
                'invogue_fashiontopics_partiesevents':{n: "partiesevents"},
                'invogue_fashiontopics_fashionclassroom':{n: "fashionclassroom"}
              }},
              'invogue_vogueinbeauty':{n:'invogue_vogueinbeauty', sub:{
                'invogue_vogueinbeauty_makeupconfidential':{n: "makeupconfidential"},
                'invogue_vogueinbeauty_skincaretips':{n: "skincaretips"},
                'invogue_vogueinbeauty_beautymoments':{n: "beautymoments"},
                'invogue_vogueinbeauty_aq':{n: "aq"}
              }},
              'invogue_magazine':{n:'invogue_magazine', sub:{
                'invogue_magazine_currentissue':{n: "currentissue"},
                'invogue_magazine_behindthescenes':{n: "behindthescenes"},
                'invogue_magazine_voguecontributors':{n: "voguecontributors"}
              }},
              'invogue_bestshows':{n:'invogue_bestshows', sub:{
                'invogue_magazine_catwalkpicks':{n: "catwalkpicks"}
              }}
            }},
	        product:{n:'product'},
	        brand:{n:'brand'}
        };
        this.mtkReferers = ["t.sina.com.cn", "t.qq.com", "www.9911.com", "tieba.baidu.com", "voguewebsite.blog.163.com", "www.douban.com", "www.kaixin001.com",
            "www.1188.com", "www.114la.com", "bjdns2.cncmax.cn:8080", "www.haokan123.com", "www.go2000.cn", "www.wo114.com", "www.365j.com","www.qq5.com",
            "www.go2000.com", "pppdd.com", "hao.360.cn", "www6.1616.net", "chinadaily.com.cn", "t.sina.com.cn", "luxury.msn.com.cn","www.0460.com",
            "hao123.com", "ubcpm.com", "hap1.ucweb.com.cn:8040","www.1166.com", "www.6789.com","www.d4000.com","www.vv6v.com","www.im265.cn", "www.371dh.com"
        ];
    }
    ChannelDetector.prototype.getChannel = function(uri, obj, ret) {
        if(uri) {
		    if(obj[uri] && obj[uri].n) {
			    ret.push(obj[uri].n);
			    return true;
		    } else {
			    for(var i in obj) {
				    if(obj[i]['sub']) { 
					    if(this.getChannel(uri, obj[i]['sub'], ret)) {
					        ret.push(obj[i]['n']);
						    return true;
					    }
				    }
			    }
		    }
	    }
	    return false;
    }
    ChannelDetector.prototype.detectChannel = function(pageTracker) {
        var ret = this.getDomainUri(location.href);
	    if(ret) {
		    var domainName = ret[1];
		    //if uri start with 'index' or it's '', it's homepage
		    var uri = ret[2] ? ret[2] : 'homePage';
            uri = uri.toLowerCase();
		    if(uri == "homepage" || uri == 'index'  || (uri.length > 5 && uri.substring(0,5) == 'index')) {
			    uri = 'homePage';
		    } else if(uri.toLowerCase() == "order_vogue.php") {
			    uri = "order_vogue";
		    } else if(uri.toLowerCase() == "rss.html") {
			    uri = "rss";
		    } else if(uri.toLowerCase() == "voguevideo_list.php?channel=12") {
			    uri = "Video_FengGeHui";
		    } else if(uri.toLowerCase() == "voguevideo_list.php?channel=5") {
			    uri = "Video_ShiZhuangXiuChang";
		    } else if(uri.toLowerCase() == "voguevideo_list.php?channel=6") {
			    uri = "Video_ShiZhuangPaiDui";
		    }
		    if(domainName != 'www.vogue.com.cn') {
                var subDomain = this.getSubDomain(domainName);
                if("shows.trends.fashion.beauty.people.jewel.feature.info.vedio.gallery.bbs.blog.whatsvogue.chinadaily.invogue.product.brand".indexOf(subDomain) != -1) {
                    if(uri == 'homePage' || "blog.bbs.product.brand.gallery".indexOf(subDomain) != -1) {
					    pageTracker._setCustomVar(1, 'VogueChannel', subDomain, 1);
				    }
                    else {
                        //replace "/" to "_" for sub channel of an individual domain
                        uri = subDomain + "_" + uri;
					    this.setChannelChain(pageTracker, uri);
				    }
			    } 
			    else {
			        pageTracker._setCustomVar(1, 'VogueChannel', domainName, 1);
			    }
		    } else {
			    this.setChannelChain(pageTracker, uri);
		    }
	    }
    }

    ChannelDetector.prototype.setChannelChain = function(pageTracker, uri) {
	    var chain = [];
	    this.getChannel(uri, this.channelMapper, chain);
	    var k = 1;
	    for(var i=chain.length-1; i>=0; i--) {
		    if(i == chain.length-1) {
			    pageTracker._setCustomVar(chain.length-i, 'VogueChannel', chain[i], 1);
		    } else {
			    pageTracker._setCustomVar(chain.length-i, 'VogueChannel-'+ (k++), chain[i], 1);
		    }
	    }
    }
    
    ChannelDetector.prototype.getDomainUri = function(url) {
	    //match the sub channel for single domain    
	    var p1 = /[\/\/]([.a-zA-z-0-9:]+?)\/([^\/]*)/;   
	    var p2 = /[\/\/]([.a-zA-Z-0-9:]+?)\/([^\/]*)\//;
	    var ret = url.match(p1);
	    if(p2.test(url)) {
		    ret = url.match(p2);
	    }
	    if(ret)
	    {
	        //invogue model: channel/sub_channel/...
		    if(ret[1] == "invogue.vogue.com.cn") {
			    var p3 = /[\/\/]([.a-zA-z-0-9:]+?)\/([^\/]*)\/([^\/]*)/;    
			    var p4 = /[\/\/]([.a-zA-Z-0-9:]+?)\/([^\/]*)\/([^\/]*)\//;
			    if(p3.test(url)) {
			        var ret = url.match(p3);
				    if(p4.test(url)) {
					    ret = url.match(p4);
				    }
				    ret[2] = ret[3] ? ret[2]+"_"+ret[3] : ret[2]
			    }
		    }
	    }
	    return ret;
    }

    ChannelDetector.prototype.getSubDomain = function(domainName) {        
	    var subDomain = domainName;
        var subs = domainName.match(/([^\.]+)\.vogue\.com\.cn/);
        if(subs) {
            subDomain = subs[1].toLowerCase();
        }
        return subDomain;
    }

    ChannelDetector.prototype.isMktSource = function() {
        var mtkKey = "__v__s__";
        var mtkValue = "mtk"
        var cookieDomain = "vogue.com.cn";
        if(cookies.get(mtkKey) == mtkValue) {
            return true;
        }
        var lc = location.href;	
	    var p1 = /[\/\/]([.a-zA-z-0-9]+?)\/([\S]*)/;
	    var testRet = lc.match(p1);
	    //filter out the promotion url
	    if(testRet) {
		     var url = testRet[2];
		     var spos = url.lastIndexOf('/');
		     if(spos >0) {
			     url = url.substring(spos + 1);
		     }
		     if(url && (/id=00[0-9]+/.test(url) || /index[0-9]+.html/.test(url))) {
			     //it's a promotion url, log it in cookie
                 cookies.put(mtkKey, mtkValue, cookieDomain);
			     return true;
		     }
	    }
        var ret = this.getDomainUri(lc);
        if(ret) {
            var subDomain = this.getSubDomain(ret[1])
            if("events.vote".indexOf(subDomain) != -1) {
                cookies.put(mtkKey, mtkValue, cookieDomain);
                return true;
            }
        }
        //EDM
        if(lc.indexOf("utm_source=")!=-1 && lc.indexOf("utm_medium") !=-1) {
            cookies.put(mtkKey, mtkValue, cookieDomain);
            return true;
        }
        ret = this.getDomainUri(document.referrer)
        if(ret) {
            domainName = ret[1];
            if(this.mtkReferers.join("/").indexOf(domainName) != -1) {
                cookies.put(mtkKey, mtkValue, cookieDomain);
                return true;
            }
        }
        return false;
    }

    var cookies = {};
    cookies.get = function(a) {
        a = a + "=";
        for (var b = document.cookie.split(";"), c = 0; c < b.length; c++) {
            for (var f = b[c]; f.charAt(0) == " ";) f = f.substring(1, f.length);
            if (f.indexOf(a) == 0) return f.substring(a.length, f.length)
        }
        return null
    };

    cookies.put = function(a, b, c) {
        document.cookie = a + "=" + b + "; path=/; domain="+c
    };

    window._v_c_d_ = window._v_c_d_ ? window._v_c_d_ : (new ChannelDetector)
    window.detectChannel = function(tracker){
    	_v_c_d_.detectChannel(tracker);
    }
})();
